package com.cloud.bssp.juc.reetrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description： 条件变量
 * @author：weirx
 * @date：2021/12/21 14:25
 * @version：3.0
 */
public class ConditionTest {

    static ReentrantLock lock = new ReentrantLock();

    static Condition Tom = lock.newCondition();

    static Condition Jerry = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {

        new Thread(() -> {

            try {
                lock.lock();
                Tom.await();
                System.out.println("吃到了鱼");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {

            try {
                lock.lock();
                Jerry.await();
                System.out.println("吃到了奶酪");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        TimeUnit.SECONDS.sleep(1);

        try {
            lock.lock();
            System.out.println("鱼来了");
            Tom.signal();
        } finally {
            lock.unlock();
        }

        TimeUnit.SECONDS.sleep(1);
        try {
            lock.lock();
            System.out.println("奶酪来了");
            Jerry.signal();
        } finally {
            lock.unlock();
        }
    }
}
